<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :height="tableHeight"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :default-sort="{prop: 'sort', order: 'ascending'}"
    >
      <el-table-column fixed="left" label="序号" prop="sort" sortable align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="按钮名称" min-width="150px" align="center">
        <template slot-scope="scope">
          <el-button :type="scope.row.backColor | btnFilter" size="mini"><font-awesome-icon v-if="scope.row.iCon" :icon="scope.row.iCon | btnIconFilter" fixed-width />{{ scope.row.btnName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="按钮ID" width="150px" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.btnID }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="编号" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.isEffective | statusFilter">
            <i v-if="row.isEffective" class="el-icon-check" />
            <i v-else class="el-icon-close" style="right:0" />
            {{ row.isEffective?'有效':'无效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleModifyStatus(row,'deleted')">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="2vh">
      <el-form ref="dataForm" :inline="true" class="demo-form-inline" :rules="rules" :model="temp" label-position="right" label-width="120px">
        <el-form-item label="按钮名称" prop="btnName">
          <el-input v-model="temp.btnName" />
        </el-form-item>
        <el-form-item label="按钮ID" prop="btnID">
          <el-input v-model="temp.btnID" />
        </el-form-item>
        <el-form-item label="按钮类型">
          <el-select v-model="temp.btnType" class="filter-item" placeholder="请选择">
            <el-option v-for="item in btnOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="模块分类">
          <el-select v-model="temp.moldID" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.text" :label="item.text" :value="item.val" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有效" style="display:inline-block;">
          <el-checkbox v-model="temp.isEffective" />
        </el-form-item>
        <el-form-item label="背景颜色" class="input-width-full">
          <el-button v-for="btnItem in btnBackgrounds" :key="btnItem.type" :type="btnItem.type" size="mini" @click="selectBackground(btnItem.backColor)"><font-awesome-icon v-if="temp.backColor===btnItem.backColor" :icon="['fas', 'check']" fixed-width /></el-button>
        </el-form-item>
        <el-form-item label="按钮图标" class="input-width-full">
          <font-awesome-icon v-for="iconItem in btnIcons" :key="iconItem.icon" :icon="[iconItem.type, iconItem.icon]" :class="{'iconActive': iconItem.icon===iConSelect}" class="icon" fixed-width @click="selectIcon(iconItem)" />
        </el-form-item>
        <el-form-item label="备注说明" class="input-width-full">
          <el-input v-model="temp.memo" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics" top="2vh">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { AddBtn, GetBtns, EditBtn, DeleteBtn } from '@/api/system'
import waves from '@/directive/waves' // Waves directive
import * as R from 'ramda'

export default {
  name: 'ComplexTable',
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = status ? 'success' : 'danger'
      return statusMap
    },
    btnFilter(type) {
      const btnMap = {
        'primary': 'primary',
        'success': 'success',
        'warning': 'warning',
        'danger': 'danger',
        'info': 'info',
        'text': 'text',
        'btn-primary': 'primary',
        'btn-success': 'success',
        'btn-warning': 'warning',
        'btn-danger': 'danger',
        'btn-info': 'info',
        'btn-default': 'text'
      }
      return btnMap[type]
    },
    btnIconFilter(icon) {
      if (icon) {
        const iconStr = icon.split(' ')
        const iconFirst = iconStr[0]
        const iconSecond = iconStr[iconStr.length - 1].match(/fa-(\S*)/)
        if (!iconSecond) {
          return [iconFirst, iconStr[1]]
        }
        let iconContent = iconSecond[1]
        if (/-o/.test(iconContent)) {
          iconContent = (iconContent.match(/(\S*)-o/))[1]
        }
        if (iconContent === 'refresh') {
          iconContent = 'sync-alt'
        }
        if (iconContent === 'floppy') {
          iconContent = 'save'
        }
        if (iconContent === 'files') {
          iconContent = 'copy'
        }
        if (iconContent === 'cloud-download') {
          iconContent = 'cloud-download-alt'
        }
        return [iconFirst, iconContent]
      }
      return ['far', 'folder-open']
    }
  },
  props: {
    tableHeight: {
      type: Number,
      default: 500
    },
    tableNode: {
      type: Object,
      default: (val) => {
        return {
          selected: true,
          title: ''
        }
      }
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      btnOptions: ['系统', '其它'],
      statusOptions: [{ text: '无', val: null }, { text: '新增/编辑', val: 'addWindow' }, { text: '配置弹窗', val: 'configWindow' }, { text: '重置密码', val: 'resetPswWindow' }, { text: '角色用户', val: 'roleUserWindow' }, { text: '角色权限', val: 'roleLimitWindow' }, { text: '查看', val: 'lookOverWindow' }, { text: '打印', val: 'printWindow' }, { text: '复制周占比', val: 'copyWindow' }, { text: '批量设置标准SKC', val: 'setskcWindow' }, { text: '岗位用户', val: 'postUserWindow' }, { text: '营销权限', val: 'marketPowerWindow' }, { text: '渠道权限', val: 'channelPowerWindow' }],
      showReviewer: false,
      temp: {
        backColor: '',
        btnEvent: null,
        btnID: '',
        btnName: '',
        btnType: false,
        cssID: 0,
        iCon: null,
        id: 0,
        isEffective: true,
        isRemove: true,
        memo: '',
        moldID: null,
        sort: 0
      },
      iConSelect: '',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑按钮',
        create: '新增按钮'
      },
      dialogPvVisible: false,
      pvData: [],
      btnBackgrounds: [{ backColor: 'btn-default', type: '' }, { backColor: 'btn-primary', type: 'primary' }, { backColor: 'btn-success', type: 'success' }, { backColor: 'btn-info', type: 'info' }, { backColor: 'btn-warning', type: 'warning' }, { backColor: 'btn-danger', type: 'danger' }],
      btnIcons: [{ type: 'fa', icon: 'sync' }, { type: 'fa', icon: 'plus' }, { type: 'fa', icon: 'edit' }, { type: 'fa', icon: 'cog' }, { type: 'fa', icon: 'minus' }, { type: 'fa', icon: 'eraser' }, { type: 'fa', icon: 'users' }, { type: 'fa', icon: 'exclamation-triangle' }, { type: 'fa', icon: 'download' }, { type: 'fa', icon: 'folder-open' }, { type: 'fa', icon: 'upload' }, { type: 'fas', icon: 'cloud-download-alt' }, { type: 'fa', icon: 'search' }, { type: 'fa', icon: 'clone' }, { type: 'fa', icon: 'save' }],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        btnName: [{ required: true, message: '模块名称不能为空', trigger: 'change' }],
        btnID: [{ required: true, message: '模块编码不能为空', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      GetBtns().then(response => {
        this.list = response.data
        this.total = response.data.length
        this.listLoading = false
      })
    },
    handleModifyStatus(row, status) {
      DeleteBtn(row.id).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
        var isEven = n => n.id !== row.id
        this.list = R.filter(isEven)(this.list)
        this.$emit('getTreeData')
      })
    },
    resetTemp() {
      this.temp = {
        backColor: 'btn-default',
        btnEvent: null,
        btnID: '',
        btnName: '',
        btnType: '',
        cssID: 0,
        iCon: null,
        id: 0,
        isEffective: true,
        isRemove: true,
        memo: '',
        moldID: null,
        sort: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempParma = this.temp
          tempParma.superiorModule = this.temp.id
          tempParma.id = 0
          tempParma.btnType = this.temp.btnType === '系统' ? 1 : 2
          AddBtn(tempParma).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.btnType = this.temp.btnType === false ? '系统' : '其它'
      if (row.iCon) {
        const iconArray = row.iCon.split(' ')
        this.iConSelect = iconArray.length > 1 ? iconArray[1] : iconArray[0]
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          if (tempData.btnType === '系统') {
            tempData.btnType = false
          } else {
            tempData.btnType = true
          }
          EditBtn(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$emit('getTreeData')
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    selectBackground(backColor) {
      this.temp.backColor = backColor
    },
    selectIcon(iconItem) {
      this.iConSelect = iconItem.icon
      this.temp.iCon = `${iconItem.type} ${iconItem.icon}`
    }
  }
}
</script>

<style>
.app-container {
  height: 100%;
}
.input-width-full {
  display: block;
  width: 100%;
}
.icon {
  cursor: pointer;
  margin-right: 10px;
  transition: all 0.5s;
}

.iconActive {
  color: red;
  font-size: 18px;
}
.icon:hover {
  color: red;
  font-size: 18px;
}
.input-width-full .el-form-item__content {
  width: 75%;
}
</style>
